package com.example.administrator.liveapp.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.administrator.liveapp.ApplicationUtils;
import com.example.administrator.liveapp.R;
import com.example.administrator.liveapp.Xutils3.MyCallBack;
import com.example.administrator.liveapp.Xutils3.XUtils;
import com.example.administrator.liveapp.bean.OrderDetailsBean;
import com.example.administrator.liveapp.utils.AppUrl;
import com.example.administrator.liveapp.utils.TimeChangeUtil;
import com.example.administrator.liveapp.view.FullyLinearLayoutManager;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单详情activity
 */

public class OrderDetails extends AppCompatActivity implements View.OnClickListener {

    private TextView text_name;//收货人
    private TextView text_phone;//联系方式
    private TextView text_detailed_address;//详细地址
    private TextView payments_tatus;//订单状态
    private TextView sum;//小计
    private TextView freight;//运费
    private TextView orderNumber;//订单编号
    private TextView order_time;//创建时间
    private TextView storetel;//联系客服
    private TextView pay_price;//合计
    private TextView submit_orders;//立即支付
    private RecyclerView Orders_recycle;//订单商品列表
    private String goodsOrder;//订单编号
    private OrderDetailsBean bean;
    private RelativeLayout rl_bottom;
    private View loadView;//loding页面（加载页）


    //支付
    private PopupWindow mPopWindow;
    private Button payButton;
    private ImageView zhifubao;
    private ImageView weixin;
    private IWXAPI mIwxapi;
    private TextView moneys;
    private LinearLayout booking_layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.orderdetails);
        initView();
        setData();
    }

    private void initView() {
        Intent intent = getIntent();
        goodsOrder = intent.getStringExtra("goodsOrder");
        text_name = (TextView) findViewById(R.id.text_name);
        text_phone = (TextView) findViewById(R.id.text_phone);
        text_detailed_address = (TextView) findViewById(R.id.text_detailed_address);
        payments_tatus = (TextView) findViewById(R.id.payments_tatus);
        sum = (TextView) findViewById(R.id.sum);
        freight = (TextView) findViewById(R.id.freight);
        orderNumber = (TextView) findViewById(R.id.orderNumber);
        order_time = (TextView) findViewById(R.id.order_time);
        storetel = (TextView) findViewById(R.id.storetel);
        pay_price = (TextView) findViewById(R.id.pay_price);
        submit_orders = (TextView) findViewById(R.id.submit_orders);
        Orders_recycle = (RecyclerView) findViewById(R.id.Orders_recycle);
        rl_bottom = (RelativeLayout) findViewById(R.id.rl_bottom);
        loadView = findViewById(R.id.loadView);
        findViewById(R.id.address_returns).setOnClickListener(this);
        storetel.setOnClickListener(this);
        submit_orders.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setData();
    }

    java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");//精确到小数点后两位
    private void setData() {
        String url = AppUrl.URL + AppUrl.OrderDetailsURL;
        Map<String,String> map = new HashMap<>();
        map.put("goodsOrder",goodsOrder);
        XUtils.Get(url,map,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Gson gson = new Gson();
                bean = gson.fromJson(result, OrderDetailsBean.class);
                text_name.setText("收货人："+bean.getOrderInfo().getNickname());
                text_phone.setText(bean.getOrderInfo().getTelnumber());
                text_detailed_address.setText("收货地址："+bean.getOrderInfo().getAddress());
                sum.setText("¥ "+bean.getOrderInfo().getTotalprice());
                if(bean.getOrderInfo().getFreight().equals("0")){
                    freight.setText("免邮");
                }else{
                    freight.setText("¥ "+bean.getOrderInfo().getFreight());
                }
                orderNumber.setText(goodsOrder);
                order_time.setText(TimeChangeUtil.getStrTime(bean.getOrderInfo().getOrderaddtime()));
                pay_price.setText("合计:¥ " + df.format(Double.parseDouble(bean.getOrderInfo().getTotalprice())+Double.parseDouble(bean.getOrderInfo().getFreight())));
                if (bean.getOrderInfo().getBookorderstatus().equals("0")) {
                    payments_tatus.setText("待支付");
                    pay_price.setVisibility(View.VISIBLE);
                    submit_orders.setText("立即支付");
                } else if (bean.getOrderInfo().getBookorderstatus().equals("1")) {
                    payments_tatus.setText("已支付");
                    pay_price.setVisibility(View.GONE);
                    submit_orders.setText("立即退款");
                }else if(bean.getOrderInfo().getBookorderstatus().equals("2")){
                    payments_tatus.setText("交易取消");
                    rl_bottom.setVisibility(View.GONE);
                }else if(bean.getOrderInfo().getBookorderstatus().equals("3")){
                    payments_tatus.setText("已退款");
                    rl_bottom.setVisibility(View.GONE);
                }else if(bean.getOrderInfo().getBookorderstatus().equals("4")){
                    payments_tatus.setText("退款中");
                    rl_bottom.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }

            @Override
            public void onFinished() {
                super.onFinished();
                FullyLinearLayoutManager linearlayout = new FullyLinearLayoutManager(OrderDetails.this);
                linearlayout.setScrollEnabled(false);
                Orders_recycle.setHasFixedSize(true);
                Orders_recycle.setLayoutManager(linearlayout);
                OrdersBook book = new OrdersBook(bean.getBook());
                Orders_recycle.setAdapter(book);
                loadView.setVisibility(View.GONE);
            }
        });
    }


    class OrdersBook extends RecyclerView.Adapter<OrderDetails.OrdersBook.ViewHolder> {
        public Context context;
        List<OrderDetailsBean.BookBean> book;

        public OrdersBook(List<OrderDetailsBean.BookBean> book) {
            this.book = book;
        }


        @Override
        public OrderDetails.OrdersBook.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ordersbook_item, null);
            OrderDetails.OrdersBook.ViewHolder viewHolder = new OrderDetails.OrdersBook.ViewHolder(view);
            context = parent.getContext();
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Glide.with(context).load(AppUrl.URL + book.get(position).getBookBannerImg().substring(1, book.get(position).getBookBannerImg().indexOf("|"))).into(holder.shopping_book_image);
            holder.shopping_book_name.setText(book.get(position).getBookTitle());
            holder.shopping_book_money.setText("¥" + book.get(position).getPrice());
            holder.shopping_book_number.setText("×" + book.get(position).getNum());
        }

        @Override
        public int getItemCount() {
            return book.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public RoundedImageView shopping_book_image;
            public TextView shopping_book_name;
            public TextView shopping_book_money;
            public TextView shopping_book_number;

            public ViewHolder(View itemView) {
                super(itemView);
                shopping_book_image = (RoundedImageView) itemView.findViewById(R.id.shopping_book_image);
                shopping_book_name = (TextView) itemView.findViewById(R.id.shopping_book_name);
                shopping_book_money = (TextView) itemView.findViewById(R.id.shopping_book_money);
                shopping_book_number = (TextView) itemView.findViewById(R.id.shopping_book_number);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.storetel://联系客服
                call(bean.getOrderInfo().getStoretel());
                break;
            case R.id.address_returns://退出
                finish();
                break;
            case R.id.submit_orders:
                if(bean.getOrderInfo().getBookorderstatus().equals("0")){//支付
                    showPopupWindow();
                }else if(bean.getOrderInfo().getBookorderstatus().equals("1")){//退款
                    Intent intent = new Intent(OrderDetails.this,RefundReasonActivity.class);
                    intent.putExtra("goodsOrder",goodsOrder);
                    intent.putExtra("orderPrice",df.format(Double.parseDouble(bean.getOrderInfo().getTotalprice())+Double.parseDouble(bean.getOrderInfo().getFreight())));
                    startActivity(intent);
                }
                break;
            case R.id.pay_button://确认支付
                requestPay();
                break;
            case R.id.zhifubao:
                zhifubao.setImageResource(R.drawable.check);
                weixin.setImageResource(R.drawable.no_check);
                break;
            case R.id.weixin:
                weixin.setImageResource(R.drawable.check);
                zhifubao.setImageResource(R.drawable.no_check);
                break;
        }
    }

    /**
     * 调用拨号界面
     *
     * @param tel 电话号码
     */
    private void call(String tel) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
    }



    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(OrderDetails.this).inflate(R.layout.appointment_pay_popwindow_page, null);
        mPopWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.drawable.trans, null);
        mPopWindow.setBackgroundDrawable(drawable);
        mPopWindow.setOutsideTouchable(true);
        payButton = (Button) contentView.findViewById(R.id.pay_button);
        zhifubao = (ImageView) contentView.findViewById(R.id.zhifubao);
        weixin = (ImageView) contentView.findViewById(R.id.weixin);
        moneys = (TextView) contentView.findViewById(R.id.money);
        moneys.setText(pay_price.getText());
        zhifubao.setOnClickListener(this);
        weixin.setOnClickListener(this);
        payButton.setOnClickListener(this);
        //设置各个控件的点击响应

        //显示PopupWindow
        View rootview = LayoutInflater.from(OrderDetails.this).inflate(R.layout.booking_detailspage, null);
        showPopmenu(rootview);
    }

    private void showPopmenu(View rootview) {
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        // 显示窗口位置
        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        // 设置layout在PopupWindow中显示的位置
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);
    }

    /**
     * 微信支付
     */
    private void requestPay() {
        String url = AppUrl.URL + AppUrl.payUrl;
        Map<String,String> map = new HashMap<>();
        map.put("body","半书房大学");
        map.put("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
        map.put("goodsOrder",bean.getOrderInfo().getGoodsorder() );
        // 微信
        XUtils.Get(url, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                JSONObject obj = null;
                try {
                    obj = new JSONObject(result);
                    // 微信支付回调
                    setWeChat(obj);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                Toast.makeText(OrderDetails.this, ex.getMessage()+"1", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinished() {
                super.onFinished();
                finish();
            }
        });
    }

    /**
     * 微信支付
     */
    private void setWeChat(JSONObject obj) {
        mIwxapi = WXAPIFactory.createWXAPI(this, obj.optString("appid"));
        mIwxapi.registerApp(obj.optString("appid"));// 将应用注册到微信
        if (mIwxapi != null && mIwxapi.isWXAppInstalled()) {// 判断用户有没有安装微信
            PayReq req = new PayReq();
            req.appId = obj.optString("appid");
            req.partnerId = obj.optString("partnerid");
            req.prepayId = obj.optString("prepayid");
            req.nonceStr = obj.optString("noncestr");
            req.timeStamp = obj.optString("timestamp");
            req.packageValue = obj.optString("package");
            req.sign = obj.optString("sign");
            // req.extData = "app data";// 可选
            mIwxapi.sendReq(req);
        } else {
            Toast.makeText(this, "用户未安装微信", Toast.LENGTH_SHORT).show();
            return;
        }
    }
}
